
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';

import '../../common_ui/loading.dart';
import '../../repository/sjx_api.dart';

class RegisterViewModel with ChangeNotifier {
  bool _isAgreed = false; // 是否同意协议状态
  String _phoneNumber = '';
  String _password = '';
  String _codeNumber = '';
  int _countdown = 0;
  bool _isCounting = false;

  bool get isAgreed => _isAgreed;
  String get phoneNumber => _phoneNumber;
  String get password => _password;
  int get countdown => _countdown;
  bool get isCounting => _isCounting;
  String get codeNumber => _codeNumber;

  // 添加导航回调
  VoidCallback? _onRegisterSuccess;

  // 设置回调
  void setOnRegisterSuccess(VoidCallback callback) {
    _onRegisterSuccess = callback;
  }

  void updatePhoneNumber(String number) {
    _phoneNumber = number;
  }

  void updatePassword(String password) {
    _password = password;
  }

  void updateCodeNumber(String number) {
    _codeNumber = number;
  }

  void toggleAgreement() {
    _isAgreed = !_isAgreed;
    notifyListeners(); // 通知监听者状态已改变
  }

  void setAgreed(bool value) {
    if (_isAgreed != value) {
      _isAgreed = value;
      notifyListeners();
    }
  }

  bool _isValidPhoneNumber() {
    if (_phoneNumber.isEmpty) return false;
    // 简单的手机号格式验证（11位数字，1开头）
    final regex = RegExp(r'^1[3-9]\d{9}$');
    return regex.hasMatch(_phoneNumber);
  }

  //点击登录按钮
  Future<void> registerPress() async {
    if (!_isAgreed) {
      showToast('请先同意用户协议和隐私政策');
      return;
    }
    if (_phoneNumber.isEmpty) {
      showToast('请输入手机号码');
      return;
    }
    if (!_isValidPhoneNumber()) {
      showToast('请输入正确的手机号码');
      return;
    }
    if (_codeNumber.isEmpty) {
      showToast('请输入验证码');
      return;
    }
    if (_password.isEmpty) {
      showToast('请输入密码');
      return;
    }
    Loading.showLoading();
    bool result = await SJXApi.instance().register(_phoneNumber, _password, _codeNumber);
    if (result) {
      //注册成功
      Loading.dismissAll();
      showToast('注册成功');
      _onRegisterSuccess?.call();
    } else {
      showToast('注册失败');
    }
  }

  //获取验证码
  Future<void> getPhoneCode() async {
    if (!_isAgreed) {
      showToast('请先同意用户协议和隐私政策');
      return;
    }
    if (_phoneNumber.isEmpty) {
      showToast('请输入手机号码');
      return;
    }
    if (!_isValidPhoneNumber()) {
      showToast('请输入正确的手机号码');
      return;
    }

    await SJXApi.instance().phoneCode(_phoneNumber);
    startCountdown();
  }

  //开始获取验证码倒计时
  Future<void> startCountdown() async {
    if (!_isAgreed) {
      showToast('请先同意用户协议和隐私政策');
      return;
    }
    if (_isCounting) return;

    _isCounting = true;
    _countdown = 60;
    notifyListeners();

    while (_countdown > 0) {
      await Future.delayed(const Duration(seconds: 1));
      _countdown--;
      notifyListeners();
    }

    _isCounting = false;
  }
}